<?php
require_once('../includes/init.php');

$act = (isset($_REQUEST['act']) && $_REQUEST['act'] <> '') ? $_REQUEST['act'] : 'AddressEdit';
if ($act == 'AddressEdit')
{
    $rs_arr = array(
        'code' => '200',
        'msg'  => ''
    );
    if($_SESSION[SESSION_PREFIX]['user_id']<>'' && $_SESSION[SESSION_PREFIX]['user_id']<>'0')
	{
        $sql = "SELECT `region_name` FROM `region` WHERE `region_id`='".$_POST['cprovince']."';";
        $province = $db->getOne($sql);
        $sql = "SELECT `region_name` FROM `region` WHERE `region_id`='".$_POST['ccity']."';";
        $city = $db->getOne($sql);
        $sql = "SELECT `region_name` FROM `region` WHERE `region_id`='".$_POST['cvilliage']."';";
        $district = $db->getOne($sql);

		$sql = "SELECT `address_id`,`user_id`,`consignee`,`province`,`city`,`district`,`address`,`mobile`,`tel`,`is_default` FROM `user_address` WHERE `address_id`='".$_POST['id']."' AND `user_id`='".$_SESSION[SESSION_PREFIX]['user_id']."'";
		$address = $db->getRow($sql);
        if($_POST['isDefaultAddress']=='1')
        {
            $sql = "UPDATE `user_address` SET `is_default`='0' WHERE `user_id`='".$_SESSION[SESSION_PREFIX]['user_id']."';";
            $db->query($sql);
        }
		if(empty($address))
		{
            $sql = "INSERT INTO `user_address` SET `consignee`='".$_POST['userName']."',".
                   "`province`='".$_POST['cprovince']."',`city`='".$_POST['ccity']."',".
                   "`district`='".$_POST['cvilliage']."',`address`='".$_POST['address_info']."',".
                   "`province_txt`='".$province."',`city_txt`='".$city."',`district_txt`='".$district."',".
                   "`mobile`='".$_POST['mobile']."',`tel`='".$_POST['tel']."',".
                   "`is_default`='".$_POST['isDefaultAddress']."',".
                   "`user_id`='".$_SESSION[SESSION_PREFIX]['user_id']."',`add_tm`=NOW(),`update_tm`=NOW();";
			$db->query($sql);
		}
		else
		{
            $sql = "UPDATE `user_address` SET `consignee`='".$_POST['userName']."',".
                "`province`='".$_POST['cprovince']."',`city`='".$_POST['ccity']."',".
                "`district`='".$_POST['cvilliage']."',`address`='".$_POST['address_info']."',".
                "`province_txt`='".$province."',`city_txt`='".$city."',`district_txt`='".$district."',".
                "`mobile`='".$_POST['mobile']."',`tel`='".$_POST['tel']."',".
                "`is_default`='".$_POST['isDefaultAddress']."',".
                "`user_id`='".$_SESSION[SESSION_PREFIX]['user_id']."',`update_tm`=NOW() WHERE `address_id`='".$_POST['id']."';";
            $db->query($sql);
		}

        $rs_arr = array(
            'code' => '200',
            'sql' => $sql
        );
        die(json_encode($rs_arr));
	}
	else
	{
        $rs_arr = array(
            'code' => '-2',
            'msg'  => '请先登录，或者您已登录超时。'
        );
        die(json_encode($rs_arr));
	}
}else if ($act == 'GetAddressList'){
    $sql = "SELECT * FROM `user_address` WHERE `user_id`='".$_SESSION[SESSION_PREFIX]['user_id']."';";
    $address_list = $db->getAll($sql);
    $rs_arr = array(
        'code' => '200',
        'data'  => $address_list
    );
    die(json_encode($rs_arr));
}else if ($act == 'DelAddress'){
    $userId = $_SESSION[SESSION_PREFIX]['user_id'];
    $id = $_POST['id'];
    $sql = "delete from user_address where user_id = $userId and address_id = $id";
    $db->query($sql);
    $rs_arr = array(
        'code' => '200',
    );
    die(json_encode($rs_arr));
}else if ($act == 'SetDefault'){
        $userId = $_SESSION[SESSION_PREFIX]['user_id'];
        $id = $_POST['id'];
        $sql = "UPDATE `user_address` SET `is_default`='0' WHERE `user_id`='".$_SESSION[SESSION_PREFIX]['user_id']."';";
        $db->query($sql);

        $sql = "update user_address set is_default = 1 where user_id = $userId and address_id = $id";
        $db->query($sql);
        $rs_arr = array(
            'code' => '200',
        );
        die(json_encode($rs_arr));
}else if ($act == 'SelectAddress'){
    $sql = "SELECT * FROM `user_address` WHERE `address_id`='".$_POST['id']."' AND `user_id`='".$_SESSION[SESSION_PREFIX]['user_id']."'";
	$address = $db->getRow($sql);

    if(!$address){
        $rs_arr = array(
            'code' => '0',
        );
    }else{
        $sql = "SELECT `region_id`,`region_name`,`fc` FROM `region` WHERE `parent_id`='".$address['province']."' AND `is_show`='1' ORDER BY `fc` ASC;";
        $city_list = $db->getAll($sql);
        $city_str = '<option value="0">请选择</option>';
        foreach($city_list as $key =>$city)
        {
            $city_str .= '<option value="'.$city['region_id'].'"';
            if($address['city']==$city['region_id']){$city_str .= ' selected="selected"';}
            $city_str .= '>'.$city['fc'].$city['region_name'].'</option>';
        }
        //地区
        $sql = "SELECT `region_id`,`region_name`,`fc` FROM `region` WHERE `parent_id`='".$address['city']."' AND `is_show`='1' ORDER BY `fc` ASC;";
        $district_list = $db->getAll($sql);
        $district_str = '<option value="0">请选择</option>';
        foreach($district_list as $key2 =>$district)
        {
            $district_str .= '<option value="'.$district['region_id'].'"';
            if($address['district']==$district['region_id']){$district_str .= ' selected="selected"';}
            $district_str .= '>'.$city['fc'].$district['region_name'].'</option>';
        }

        $address["str"] = $address["consignee"] . "，" . $address["province_txt"] . "，" . $address["city_txt"] . "，" . $address["district_txt"] . "，" . $address["address"] . "，" . $address["mobile"] . "，" . $address["tel"];
        $rs_arr = array(
            'code' => '0',
            'city' => $city_str,
            'district' => $district_str,
            'data' => $address
        );
    }
    die(json_encode($rs_arr));
}elseif ($act == 'InvoiceDelete')
    //发票相关
    {
        header('Content-type:application/json');
        $rs_arr = array(
            'type' => '0',
            'msg'  => ''
        );
        if($_SESSION[SESSION_PREFIX]['user_id']<>'' && $_SESSION[SESSION_PREFIX]['user_id']<>'0')
        {
            $sql = "DELETE FROM `user_invoice` WHERE `invoice_id`='".$_POST['id']."' AND `user_id`='".$_SESSION[SESSION_PREFIX]['user_id']."';";
            if($db->query($sql))
            {
                $rs_arr = array(
                    'type' => '1',
                    'msg'  => '删除成功。'
                );
                die(json_encode($rs_arr));
            }
            else
            {
                $rs_arr = array(
                    'type' => '0',
                    'msg'  => '删除失败。'
                );
                die(json_encode($rs_arr));
            }
        }
        else
        {
            $rs_arr = array(
                'type' => '-2',
                'msg'  => '请先登录，或者您已登录超时。'
            );
            die(json_encode($rs_arr));
        }
    }
    elseif ($act == 'InvoiceSetDefault')
    {
        header('Content-type:application/json');
        $rs_arr = array(
            'type' => '0',
            'msg'  => ''
        );
        if($_SESSION[SESSION_PREFIX]['user_id']<>'' && $_SESSION[SESSION_PREFIX]['user_id']<>'0')
        {
            if($_POST['id']==0)
            {
                $sql = "UPDATE `user_invoice` SET `is_default`='0' WHERE `user_id`='".$_SESSION[SESSION_PREFIX]['user_id']."';";
                $db->query($sql);
                $rs_arr = array(
                    'type' => '1',
                    'msg'  => '更新成功。'
                );
                die(json_encode($rs_arr));
            }
    
            $sql = "SELECT * FROM `user_invoice` WHERE `invoice_id`='".$_POST['id']."' AND `user_id`='".$_SESSION[SESSION_PREFIX]['user_id']."';";
            $row = $db->getRow($sql);
            if(!empty($row))
            {
                $sql = "UPDATE `user_invoice` SET `is_default`='0' WHERE `user_id`='".$_SESSION[SESSION_PREFIX]['user_id']."';";
                $db->query($sql);
                $sql = "UPDATE `user_invoice` SET `is_default`='1' WHERE `invoice_id`='".$_POST['id']."';";
                $db->query($sql);
                $rs_arr = array(
                    'type' => '1',
                    'msg'  => '更新成功。'
                );
                die(json_encode($rs_arr));
            }
            else
            {
                $rs_arr = array(
                    'type' => '0',
                    'msg'  => '对不起，您不能编辑不属于您的发票信息。'
                );
                die(json_encode($rs_arr));
            }
        }
        else
        {
            $rs_arr = array(
                'type' => '-2',
                'msg'  => '请先登录，或者您已登录超时。'
            );
            die(json_encode($rs_arr));
        }
    }
    elseif  ($act == 'InvoiceEdit')
    {
        header('Content-type:application/json');
        $rs_arr = array(
            'type' => '0',
            'msg'  => ''
        );
        if($_SESSION[SESSION_PREFIX]['user_id']<>'' && $_SESSION[SESSION_PREFIX]['user_id']<>'0')
        {
            $sql = "SELECT `invoice_id`,`user_id`,`type`,`company`,`address`,`bank`,`account`,`tel`,`taxno`,`is_default` ".
                   "FROM `user_invoice` WHERE `invoice_id`='".$_POST['id']."' AND `user_id`='".$_SESSION[SESSION_PREFIX]['user_id']."'";
            $invoice = $db->getRow($sql);
            if(!empty($invoice))
            {
                //限制不能读取别人的地址信息
                if($invoice['user_id']==$_SESSION[SESSION_PREFIX]['user_id'])
                {
                    $rs_arr = array(
                        'type' => '1',
                        'invoice' => $invoice,
                    );
                    die(json_encode($rs_arr));
                }
                else
                {
                    $rs_arr = array(
                        'type' => '0',
                        'msg'  => '对不起，你无权读取该信息'
                    );
                    die(json_encode($rs_arr));
                }
            }
            else
            {
                $rs_arr = array(
                    'type' => '0',
                    'msg'  => '读取数据失败'
                );
                die(json_encode($rs_arr));
                //die('2');
            }
        }
        else
        {
            $rs_arr = array(
                'type' => '-2',
                'msg'  => '请先登录，或者您已登录超时。'
            );
            die(json_encode($rs_arr));
        }
    }
    elseif ($act == 'InvoiceUpdate')
    {
        header('Content-type:application/json');
        $rs_arr = array(
            'type' => '0',
            'msg'  => ''
        );
        if($_SESSION[SESSION_PREFIX]['user_id']<>'' && $_SESSION[SESSION_PREFIX]['user_id']<>'0')
        {
            $icompany    = trim($_POST['icompany']);//普票公司名称
            $company    = trim($_POST['CompanyName']);
            $address    = trim($_POST['Address']);
            $bank       = trim($_POST['OpenBank']);
            $account    = trim($_POST['BankAccount']);
            $tel        = trim($_POST['Telephone']);
            $taxno      = trim($_POST['TaxNo']);
    
            //add
            if($_POST['i_optype']=='0')
            {
                //数量控制
                $sql = "SELECT count(*) FROM `user_invoice` WHERE `user_id`='".$_SESSION[SESSION_PREFIX]['user_id']."';";
                $row = $db->getOne($sql);
                if($row>10)
                {
                    $rs_arr = array(
                        'type' => '0',
                        'msg'  => '每个账号最多只能添加10条发票信息。'
                    );
                    die(json_encode($rs_arr));
                }
    
                //普通发票
                if($_POST['itype']=='0')
                {
                    //普通发票，个人，只能有一条。存在就返回该条id，直接选择该条即可
                    if($_POST['iptype']=='0')
                    {
    
                        //检查不存在，那就设置company内容为“个人”
                        $icompany = "个人";
                    }
                    $sql = "SELECT * FROM `user_invoice` WHERE `type`='0' AND `company`='".$icompany."' AND `user_id`='".$_SESSION[SESSION_PREFIX]['user_id']."';";
                    $pp_invoice = $db->getRow($sql);
                    if(!empty($pp_invoice))
                    {
                        $rs_arr = array(
                            'type' => '2',
                            'invoice' => array(
                                'type' => '0',
                                'invoice_id' => $pp_invoice['invoice_id'],
                                'title' => $icompany,
                                'is_default' => $pp_invoice['is_default']
                            ),
                            'msg'  => '该普通发票信息已经存在，请选择。'
                        );
                        die(json_encode($rs_arr));
                    }
    
                    //检查个人不存在的，那么插入数据库，是个人的 company=个人，否则等于传入的数据
                    $sql = "INSERT INTO `user_invoice` SET `type`='0',`company`='".$icompany."',".
                        "`user_id`='".$_SESSION[SESSION_PREFIX]['user_id']."',`add_tm`=NOW(),`update_tm`=NOW();";
                    if($db->query($sql))
                    {
                        $invoice_id = $db->insert_id();
                        $nflag = '0';
                        if($_POST['IsDefault']=='1')
                        {
                            $sql = "UPDATE `user_invoice` SET `is_default`='0' WHERE `user_id`='".$_SESSION[SESSION_PREFIX]['user_id']."';";
                            $db->query($sql);
                            $sql = "UPDATE `user_invoice` SET `is_default`='1' WHERE `invoice_id`='".$invoice_id."';";
                            $db->query($sql);
                            $nflag = '1';
                        }
                        else
                        {
                            //判断只有一条地址，就是设置为默认
                            $sql = "SELECT count(*) FROM `user_invoice` WHERE `user_id`='".$_SESSION[SESSION_PREFIX]['user_id']."';";
                            $row = $db->getOne($sql);
                            if($row==1)
                            {
                                $sql = "UPDATE `user_invoice` SET `is_default`='1' WHERE `invoice_id`='".$invoice_id."';";
                                $db->query($sql);
                                $nflag = '1';
                            }
                        }
                        $rs_arr = array(
                            'type' => '1',
                            'invoice' => array(
                                'type' => '0',
                                'invoice_id' => $invoice_id,
                                'title'     => $icompany,
                                'is_default' => $nflag
                            ),
                            'msg'  => '新增普票，成功。'
                        );
                        die(json_encode($rs_arr));
                    }
                    else
                    {
                        $rs_arr = array(
                            'type' => '0',
                            'msg'  => '插入数据错误'
                        );
                        die(json_encode($rs_arr));
                    }
                }
                //增值税发票
                else
                {
                    //增值税发票只能有一条
                    // $sql = "SELECT count(*) FROM `user_invoice` WHERE `type`='1' AND `user_id`='".$_SESSION[SESSION_PREFIX]['user_id']."';";
                    // $row = $db->getOne($sql);
                    // if($row>0)
                    // {
                    //     $rs_arr = array(
                    //         'type' => '0',
                    //         'msg'  => '增值税发票只能有一个。'
                    //     );
                    //     die(json_encode($rs_arr));
                    // }
    
                    //添加
                    $sql = "INSERT INTO `user_invoice` SET `company`='".$company."',`address`='".$address."',".
                        "`bank`='".$bank."',`account`='".$account."',`tel`='".$tel."',`type`='1',".
                        "`taxno`='".$taxno."',`user_id`='".$_SESSION[SESSION_PREFIX]['user_id']."',`add_tm`=NOW(),`update_tm`=NOW();";
                    if($db->query($sql))
                    {
                        $invoice_id = $db->insert_id();
                        $nflag = '0';
    
                        if($_POST['IsDefault']=='1')
                        {
                            $sql = "UPDATE `user_invoice` SET `is_default`='0' WHERE `user_id`='".$_SESSION[SESSION_PREFIX]['user_id']."';";
                            $db->query($sql);
                            $sql = "UPDATE `user_invoice` SET `is_default`='1' WHERE `invoice_id`='".$invoice_id."';";
                            $db->query($sql);
                            $nflag = '1';
                        }
                        else
                        {
                            //判断只有一条地址，就是设置为默认
                            $sql = "SELECT count(*) FROM `user_invoice` WHERE `user_id`='".$_SESSION[SESSION_PREFIX]['user_id']."';";
                            $row = $db->getOne($sql);
                            if($row==1)
                            {
                                $sql = "UPDATE `user_invoice` SET `is_default`='1' WHERE `invoice_id`='".$invoice_id."';";
                                $db->query($sql);
                                $nflag = '1';
                            }
                        }
    
                        $rs_arr = array(
                            'type' => '1',
                            'msg'  => '新增成功。',
                            'invoice' => array(
                                'type' => '1',
                                'invoice_id' => $invoice_id,
                                'title' => $company,
                                'is_default' => $nflag
                            )
                        );
                        die(json_encode($rs_arr));
    
                    }
                    else
                    {
                        //die('3`插入数据错误！');
                        $rs_arr = array(
                            'type' => '0',
                            'msg'  => '插入数据错误'
                        );
                        die(json_encode($rs_arr));
                    }
                }
            }
            //edit
            else
            {
                if($_POST['itype']=='0')
                {
                    //普通发票，个人，只能有一条。存在就返回该条id，直接选择该条即可
                    if($_POST['iptype']=='0')
                    {
    
                        //检查不存在，那就设置company内容为“个人”
                        $icompany = "个人";
                    }
                    $sql = "SELECT * FROM `user_invoice` WHERE `type`='0' AND `company`='".$icompany."' AND `invoice_id`<>'".$_POST['id']."' AND `user_id`='".$_SESSION[SESSION_PREFIX]['user_id']."';";
                    $pp_invoice = $db->getRow($sql);
                    if(!empty($pp_invoice))
                    {
                        $rs_arr = array(
                            'type' => '2',
                            'invoice' => array(
                                'type' => '0',
                                'invoice_id' => $pp_invoice['invoice_id'],
                                'title' => $icompany,
                                'is_default' => $pp_invoice['is_default']
                            ),
                            'msg'  => '该发票名称已经存在，您不能改为该名称，请选择。'
                        );
                        die(json_encode($rs_arr));
                    }
    
                    //检查个人不存在的，那么插入数据库，是个人的 company=个人，否则等于传入的数据
                    $sql = "UPDATE `user_invoice` SET `company`='".$icompany."',`update_tm`=NOW() WHERE `invoice_id`='".$_POST['id']."';";
                    if($db->query($sql))
                    {
                        $invoice_id = $_POST['id'];
                        $nflag = '0';
                        if($_POST['IsDefault']=='1')
                        {
                            $sql = "UPDATE `user_invoice` SET `is_default`='0' WHERE `user_id`='".$_SESSION[SESSION_PREFIX]['user_id']."';";
                            $db->query($sql);
                            $sql = "UPDATE `user_invoice` SET `is_default`='1' WHERE `invoice_id`='".$invoice_id."';";
                            $db->query($sql);
                            $nflag = '1';
                        }
                        $rs_arr = array(
                            'type' => '1',
                            'invoice' => array(
                                'type' => '0',
                                'invoice_id' => $invoice_id,
                                'title'     => $icompany,
                                'is_default' => $nflag
                            ),
                            'msg'  => '修改发票成功。'
                        );
                        die(json_encode($rs_arr));
                    }
                    else
                    {
                        $rs_arr = array(
                            'type' => '0',
                            'msg'  => '更新出错'
                        );
                        die(json_encode($rs_arr));
                    }
                }
                //增值税发票更新
                else
                {
                    //增值税发票只能有一条
                    // $sql = "SELECT count(*) FROM `user_invoice` WHERE `type`='1' AND `invoice_id`<>'".$_POST['id']."' AND `user_id`='".$_SESSION[SESSION_PREFIX]['user_id']."';";
                    // $row = $db->getOne($sql);
                    // if($row>0)
                    // {
                    //     $rs_arr = array(
                    //         'type' => '0',
                    //         'msg'  => '增值税发票只能有一个。'
                    //     );
                    //     die(json_encode($rs_arr));
                    // }
    
                    //添加
                    $sql = "UPDATE `user_invoice` SET `company`='".$company."',`address`='".$address."',".
                           "`bank`='".$bank."',`account`='".$account."',`tel`='".$tel."',`taxno`='".$taxno."',".
                           "`update_tm`=NOW() WHERE `invoice_id`='".$_POST['id']."';";
                    if($db->query($sql))
                    {
                        $invoice_id = $_POST['id'];
                        $nflag = '0';
    
                        if($_POST['IsDefault']=='1')
                        {
                            $sql = "UPDATE `user_invoice` SET `is_default`='0' WHERE `user_id`='".$_SESSION[SESSION_PREFIX]['user_id']."';";
                            $db->query($sql);
                            $sql = "UPDATE `user_invoice` SET `is_default`='1' WHERE `invoice_id`='".$invoice_id."';";
                            $db->query($sql);
                            $nflag = '1';
                        }
    
                        $rs_arr = array(
                            'type' => '1',
                            'msg'  => '更新成功。',
                            'invoice' => array(
                                'type' => '1',
                                'invoice_id' => $invoice_id,
                                'title' => $company,
                                'is_default' => $nflag
                            )
                        );
                        die(json_encode($rs_arr));
    
                    }
                    else
                    {
                        //die('3`插入数据错误！');
                        $rs_arr = array(
                            'type' => '0',
                            'msg'  => '插入数据错误'
                        );
                        die(json_encode($rs_arr));
                    }
                }
            }
        }
        else
        {
            $rs_arr = array(
                'type' => '-2',
                'msg'  => '请先登录，或者您已登录超时。'
            );
            die(json_encode($rs_arr));
        }
    }
    elseif ($act == 'InvoiceList')
    {
        $sql = "SELECT * FROM `user_invoice` WHERE `user_id`='".$_SESSION[SESSION_PREFIX]['user_id']."' ORDER BY `is_default` DESC,`company`,`invoice_id` DESC;";
        $invoice_list = $db->getAll($sql);
        $rs_arr = array(
            'data' => $invoice_list
        );
        die(json_encode($rs_arr));
    }
    